package com.ruoyi.jiaopei.controller;

import java.util.List;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.jiaopei.domain.TbStudent;
import com.ruoyi.jiaopei.domain.TbUserStudent;
import com.ruoyi.jiaopei.domain.bo.BindingUserBo;
import com.ruoyi.jiaopei.domain.vo.StudentCurriculumVo;
import com.ruoyi.jiaopei.domain.vo.TbUserStudentVo;
import com.ruoyi.jiaopei.mapper.TbUserStudentMapper;
import com.ruoyi.jiaopei.service.ITbUserStudentService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.jiaopei.domain.vo.TbStudentVo;
import com.ruoyi.jiaopei.domain.bo.TbStudentBo;
import com.ruoyi.jiaopei.service.ITbStudentService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 学员
 *
 * @author macy
 * @date 2024-04-03
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/jiaopei/student")
public class TbStudentController extends BaseController {

    private final ITbStudentService iTbStudentService;
    private final ISysUserService sysUserService;
    private final TbUserStudentMapper userStudentMapper;


    @GetMapping("/queryStudentCurriculumNew")
    public TableDataInfo<StudentCurriculumVo> queryStudentCurriculumNew(TbStudentBo bo, PageQuery pageQuery) {

//        if(!LoginHelper.isAdmin()){
//            if(null!=LoginHelper.getLoginUser().getTeacher()&&"1".equals(LoginHelper.getLoginUser().getTeacher())){
//                if(null==bo.getTeacherId()){
//                    bo.setTeacherId(LoginHelper.getUserId());
//                }
//            }else if(null!=LoginHelper.getLoginUser().getTeacher()&&"2".equals(LoginHelper.getLoginUser().getTeacher())){
//                if(null==bo.getSalesId()){
//                    bo.setSalesId(LoginHelper.getUserId());
//                }
//            }
//        }


        return iTbStudentService.queryStudentCurriculumNew(bo, pageQuery);
    }



    /**
     * 查询学员列表  ( 老师权限过滤 )
     */
    @GetMapping("/list")
    public TableDataInfo<TbStudentVo> list(TbStudentBo bo, PageQuery pageQuery) {

//        if(!LoginHelper.isAdmin()){
//            if(null!=LoginHelper.getLoginUser().getTeacher()&&"1".equals(LoginHelper.getLoginUser().getTeacher())){
//                bo.setTeacherId(LoginHelper.getUserId());
//            }else if(null!=LoginHelper.getLoginUser().getTeacher()&&"2".equals(LoginHelper.getLoginUser().getTeacher())){
//                bo.setSalesId(LoginHelper.getUserId());
//            }
//        }

        return iTbStudentService.queryPageList(bo, pageQuery);
    }


    /**
     * 导出学员列表
     */
    @SaCheckPermission("jiaopei:student:export")
    @Log(title = "学员", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TbStudentBo bo, HttpServletResponse response) {
        List<TbStudentVo> list = iTbStudentService.queryList(bo);
        ExcelUtil.exportExcel(list, "学员", TbStudentVo.class, response);
    }

    /**
     * 获取学员详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("jiaopei:student:query")
    @GetMapping("/{id}")
    public R<TbStudentVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iTbStudentService.queryById(id));
    }

    /**
     * 新增学员
     */
    @SaCheckPermission("jiaopei:student:add")
    @Log(title = "学员", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TbStudentBo bo) {
        return toAjax(iTbStudentService.insertByBo(bo));
    }

    /**
     * 修改学员
     */
    @SaCheckPermission("jiaopei:student:edit")
    @Log(title = "学员", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TbStudentBo bo) {
        return toAjax(iTbStudentService.updateByBo(bo));
    }

    /**
     * 删除学员
     *
     * @param ids 主键串
     */
    @SaCheckPermission("jiaopei:student:remove")
    @Log(title = "学员", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iTbStudentService.deleteWithValidByIds(Arrays.asList(ids), true));
    }


    /**
     * 绑定家长账号
     */
    @Transactional
    @PostMapping("/bindingUser")
    public R bindingUser(@Validated(AddGroup.class) @RequestBody BindingUserBo bo) {

        userStudentMapper.delete(new LambdaQueryWrapper<TbUserStudent>()
            .eq(TbUserStudent::getStudentId, bo.getStudentId())
        );

        SysUser sysUser=sysUserService.selectUserById(bo.getUserId());
        if(null!=sysUser){
            iTbStudentService.update(new LambdaUpdateWrapper<TbStudent>()
                .eq(TbStudent::getId, bo.getStudentId())
                .set(TbStudent::getParents, sysUser.getNickName())
                .set(TbStudent::getParentsTel, sysUser.getPhonenumber())
            );

//            List<TbUserStudentVo> list=userStudentMapper.selectVoList(new LambdaQueryWrapper<TbUserStudent>()
//                .eq(TbUserStudent::getUserId,bo.getUserId())
//            );
//
//            if(null!=list&&list.size()>0){
//                List<Long> ids = list.stream().map(TbUserStudentVo::getStudentId).collect(Collectors.toList());
//
//                userStudentMapper.update(new LambdaUpdateWrapper<TbUserStudent>()
//                    .in(TbUserStudent::getStudentId,ids)
//                    .set(TbUserStudent::getUserId,sysUser.getUserId())
//                );
//
//                iTbStudentService.update(new LambdaUpdateWrapper<TbStudent>()
//                    .in(TbStudent::getId,ids)
//                    .set(TbStudent::getParents,sysUser.getNickName())
//                    .set(TbStudent::getParentsTel,sysUser.getPhonenumber())
//                );
//            }

        }

        userStudentMapper.insert(new TbUserStudent(bo.getUserId(),bo.getStudentId()));

        return R.ok();
    }
}
